<template>
  <MHeader title="设置"/>
  <van-skeleton title avatar :row="3" :loading="isLoading">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="form.nickName"
            name="用户名"
            label="用户名"
            clearable
            placeholder="用户名"
            maxlength="20"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="form.introduceSign"
            clearable
            name="个性签名"
            label="个性签名"
            maxlength="100"
            placeholder="个性签名"
        />
        <van-field
            v-model.trim="form.passwordMd5"
            clearable
            type="password"
            name="新密码"
            label="新密码"
            placeholder="新密码"
        />
        <van-button round block type="primary" native-type="submit" class="!mt-2">
          提交
        </van-button>
      </van-cell-group>
    </van-form>
  </van-skeleton>
</template>
<script setup lang="ts">
import {ref} from 'vue';
import useLoading from "@/hooks/useLoading";
import useUserDetail from "@/hooks/useUserDetail";
import updateUserInfoAPI, {type IUpdateUserInfoAPIRequestData} from "@/api/user/updateUserInfoAPI";
import {md5} from "js-md5";
import {SUCCESS_CODE} from "@/constants";
import {showSuccessToast, showToast} from "vant";
import {useRoute, useRouter} from "vue-router";
import MHeader from "@/components/MHeader/index.vue";

const {isLoading} = useLoading();
const {user, handleSearchUserDetail} = useUserDetail();
const router = useRouter();
const route = useRoute();
const form = ref<Required<IUpdateUserInfoAPIRequestData>>({
  nickName: '',
  passwordMd5: '',
  introduceSign: ''
})

const init = async () => {
  await handleSearchUserDetail();
  const {introduceSign, nickName} = user.value;
  form.value = {
    nickName,
    introduceSign,
    passwordMd5: ''
  }
}

init();


const onSubmit = async () => {
  try {
    const params: IUpdateUserInfoAPIRequestData = {
      nickName: form.value.nickName,
      introduceSign: form.value.introduceSign,
      passwordMd5: form.value.passwordMd5 !== '' ? md5(form.value.passwordMd5) : '',
    }
    let response = await updateUserInfoAPI(params)
    if (response.code === SUCCESS_CODE) {
      showSuccessToast('修改成功');
      if (form.value.passwordMd5 === '') {
        router.back();
      } else {
        const redirect = (route.query?.redirect || '') as string;
        router.push({path: `/login?redirect=${redirect}`});
      }
    }
  } catch (e: any) {
    showToast(e.message);
  } finally {
    isLoading.value = false;
  }
}
</script>